package fragments;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import ws.JSONManager;
import ws.JsonParsers;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cachopoid.R;
import com.cachopoid.activity.MainActivity;
import com.cachopoid.utils.Constantes;
import com.cachopoid.utils.GridViewAdapter;
import com.cachopoid.vo.CachopoVO;
import com.cachopoid.vo.EstablecimientoVO;
import com.cachopoid.vo.EventoVO;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;


public class FragmentEventos extends Fragment  {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
	private AdView adView;
    private static final String ARG_SECTION_NUMBER = "section_number";
    static Context mContext;
    TextView msnNohayEvents;
    static ArrayList<EventoVO> listaEventosGlobal;
    static ArrayList<CachopoVO> listaRankingCachoposGlobal;
    static ArrayList<EstablecimientoVO> ListaRankingEstablecimientosGlobal;
    static ProgressBar pbarProgresoEventos;
    GridView gridView;
    static JSONObject jsonResult = new JSONObject();
    EventoVO enventoGlobal;
    static int positionFragmentDetalleCachopo;
    View viewFragmentDetalleCachopo;
    
    
    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static FragmentEventos newInstance(int sectionNumber,MainActivity mainActivity) {
    	FragmentEventos fragment = new FragmentEventos();
    	mContext = mainActivity.getBaseContext();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public FragmentEventos() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_eventos, container, false);
        msnNohayEvents = (TextView) rootView.findViewById(R.id.TxtDetalle);
    	pbarProgresoEventos = (ProgressBar) rootView.findViewById(R.id.pbarProgresoEventos);
        Typeface font = Typeface.createFromAsset(container.getContext().getAssets(), "fuente_celta.ttf");
        msnNohayEvents.setTypeface(font);
        
        gridView = (GridView) rootView.findViewById(R.id.gridEventos);
        
        gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> a, View v, int position, long id) {
				 positionFragmentDetalleCachopo=position;
				 viewFragmentDetalleCachopo = v;
				 enventoGlobal= listaEventosGlobal.get(position);
				
				if(enventoGlobal.getIdCachopo()!=null) {
					CachopoVO cachopo = new CachopoVO();
					cachopo.setIdCachopo(enventoGlobal.getIdCachopo());
					threadCachopoMasEstablec threadCachopoMasEstabl = new threadCachopoMasEstablec(mContext);
					threadCachopoMasEstabl.execute();			
				}
				else{
					EstablecimientoVO establecimiento = new EstablecimientoVO();
					establecimiento.setIdEstablecimiento(enventoGlobal.getIdEstablecimiento());
				}
			} 
		});
        

        adView = new AdView(container.getContext());
        adView.setAdUnitId("ca-app-pub-1376388998160875/5368461942");
        adView.setAdSize(AdSize.BANNER);
        LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.anuncio);
        layout.addView(adView);
        AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
        adView.loadAd(adRequest);
        
        pbarProgresoEventos.setVisibility(View.VISIBLE);
        threadCargaEventos  threadEventos = new threadCargaEventos(container.getContext());
        threadEventos.execute();
        
       
        return rootView;
      
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
    
	  public class threadCargaEventos extends AsyncTask <Void, Integer, Boolean> {
	    	Constantes cons = new Constantes();
	    	String urlEventos = cons.HOST_SERVICIOWEB+cons.SW_OBTENER_EVENTOS;
	    	LayoutInflater l_Inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View convertView = l_Inflater.inflate(R.layout.fragment_eventos, null);
	    	

			public threadCargaEventos(Context context) {
				mContext =context;// TODO Auto-generated constructor stub
			}

			@Override
	    	protected Boolean doInBackground(Void... params) {
	    		
	    	      try{
	    	    	  pbarProgresoEventos.setVisibility(View.VISIBLE);
	    	    	  JSONManager jsonManager = new JSONManager();
	    	    	  jsonResult=jsonManager.getJSONfromURL(urlEventos,null);
	    	     }catch(Exception e){
	    	    	 
	    	     }
	    	      
	    	     return true;
	    	}
	    	
	    	@Override
	    	protected void onProgressUpdate(Integer... values) {
	 //   		 int progreso = values[0].intValue();
//	    		 pbarProgresoEventos.setProgress(progreso);
	    	}
	    	
	    	@Override
	    	protected void onPreExecute() {
	    		pbarProgresoEventos.setMax(100);
	    		pbarProgresoEventos.setProgress(0);
	    	}
	    	
	    	@Override
	    	protected void onPostExecute(Boolean result) {
	    		if(result){
	    			
	    			try {
	    				if(jsonResult != null){
	    					listaEventosGlobal=JsonParsers.parseJSONEventos(jsonResult.getJSONArray("eventos"));
	    					if(listaEventosGlobal.isEmpty()){
	    				        msnNohayEvents.setText("No hay eventos actualmente");
	    					}
	    					else{
	    						msnNohayEvents.setVisibility(View.GONE);
	    					    GridViewAdapter gridViewAdapt = new GridViewAdapter(mContext, R.layout.template_row_grid, listaEventosGlobal);
	    						gridView.setAdapter(gridViewAdapt);
	    					}
	    			    					
	    				}
	    			
	    				
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
	    			pbarProgresoEventos.setVisibility(View.GONE);	    			
	    		}
	    	}
	    	
	    	@Override
	    	protected void onCancelled() {
	    		Toast.makeText(mContext, "Carga cancelada!", Toast.LENGTH_SHORT).show();
	    	}
	    }
	  
	  
	  
	  
	  
	  public class threadCachopoMasEstablec extends AsyncTask <Void, Integer, Boolean> {
	    	Constantes cons = new Constantes();
	    	String urlCachopoMasEstablec = cons.HOST_SERVICIOWEB+cons.SW_CACHOPOMASESTABLEC;
	    	LayoutInflater l_Inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View convertView = l_Inflater.inflate(R.layout.fragment_eventos, null);
	    	

			public threadCachopoMasEstablec(Context context) {
				mContext =context;
			}

			@Override
	    	protected Boolean doInBackground(Void... params) {
	    		
	    	      try{
	    	    	 //pbarProgresoEventos.setVisibility(View.VISIBLE);
	    	    	  JSONManager jsonManager = new JSONManager();
	    	    	  jsonResult=jsonManager.getJSONfromURL(urlCachopoMasEstablec,enventoGlobal);
	    	     }catch(Exception e){
	    	    	 
	    	     }
	    	      
	    	     return true;
	    	}
	    	
	    	@Override
	    	protected void onProgressUpdate(Integer... values) {
	 //   		 int progreso = values[0].intValue();
//	    		 pbarProgresoEventos.setProgress(progreso);
	    	}
	    	
	    	@Override
	    	protected void onPreExecute() {
	    		//pbarProgresoEventos.setMax(100);
	    		//pbarProgresoEventos.setProgress(0);
	    	}
	    	
	    	@Override
	    	protected void onPostExecute(Boolean result) {
	    		if(result){
	    			
	    			try {
	    				if(jsonResult != null){
	    				
	    					listaRankingCachoposGlobal=JsonParsers.parseJSONCachopos(jsonResult.getJSONArray("cachopos"));
	    					ListaRankingEstablecimientosGlobal=JsonParsers.parseJSONEstablecimientos(jsonResult.getJSONArray("establecimientos"));
	    					//listViewRanking.setAdapter(new CachopoBaseAdapter(mContext, listaRankingCachoposGlobal, ListaRankingEstablecimientosGlobal));
	    					
	    					// Recuperar todos los datos del Cachopo 
		   					 FragmentManager fragmentManager = getFragmentManager();
		   					 fragmentManager.beginTransaction()
	   			            .replace(R.id.container, FragmentDetalleCachopos.newInstance(positionFragmentDetalleCachopo + 1,listaRankingCachoposGlobal.get(0),
	   			            		viewFragmentDetalleCachopo,ListaRankingEstablecimientosGlobal.get(0)))
	   			            .addToBackStack(null)
	   			            .commit();
		   					 
	    					if(listaEventosGlobal.isEmpty()){
	    				        
	    					}
	    					else{
	    						msnNohayEvents.setVisibility(View.GONE);
	    					    GridViewAdapter gridViewAdapt = new GridViewAdapter(mContext, R.layout.template_row_grid, listaEventosGlobal);
	    						gridView.setAdapter(gridViewAdapt);
	    					}
	    			    					
	    				}
	    			
	    				
	    			} catch (JSONException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
	    		//	pbarProgresoEventos.setVisibility(View.GONE);	    			
	    		}
	    	}
	    	
	    	@Override
	    	protected void onCancelled() {
	    		Toast.makeText(mContext, "Carga cancelada!", Toast.LENGTH_SHORT).show();
	    	}
	    }
}
